import { Component } from "react";
import { Switch, Route, Redirect } from "react-router-dom";
import { connect, ConnectedProps } from "react-redux";
import { type RootState } from "@/store";

import AppLayout from "@/layout";
import Login from "@/views/login";

class App extends Component<PropsFromRedux> {
  render() {
    return (
      <Switch>
        <Route path="/login" component={Login} />
        <Route
          path="/"
          render={(props) => {
            // 获取token
            const { token } = this.props;
            if (!token) {
              return (
                <Redirect
                  to={{
                    pathname: "/login",
                    search:
                      "redirect=" +
                      props.location.pathname +
                      props.location.search,
                  }}
                />
              );
            } else {
              return <AppLayout {...props} />;
            }
          }}
        />
      </Switch>
    );
  }
}

const connector = connect((state: RootState) => ({
  token: state.user.token,
}));

// 根据 connector 算出传递给 UI 组件的 props 类型
type PropsFromRedux = ConnectedProps<typeof connector>;

export default connector(App);
